package com.chcit.mobile.mvp.ui.fragment;

import android.content.Intent;
import android.graphics.Canvas;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.callback.ItemDragAndSwipeCallback;
import com.chad.library.adapter.base.listener.OnItemDragListener;
import com.chad.library.adapter.base.listener.OnItemSwipeListener;
import com.chcit.custom.view.spinner.EditSpinner;
import com.chcit.custom.view.text.AutofitTextView;
import com.chcit.hwmsmobile.edittext.SuperEditText;
import com.chcit.mobile.app.base.ScanFragment;
import com.chcit.mobile.app.contains.HttpMethodContains;
import com.chcit.mobile.app.utils.DialogUtil;
import com.chcit.mobile.helper.recycler.RecycleViewDivider;
import com.chcit.mobile.mvp.model.entity.Locator;
import com.chcit.mobile.mvp.model.entity.MonitorCode;
import com.chcit.mobile.mvp.model.entity.ShipmentBean;
import com.chcit.mobile.mvp.ui.adapter.MonitorCodeAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.chcit.mobile.di.component.DaggerShipmentDetailComponent;
import com.chcit.mobile.di.module.ShipmentDetailModule;
import com.chcit.mobile.mvp.contract.ShipmentDetailContract;
import com.chcit.mobile.mvp.presenter.ShipmentDetailPresenter;
import com.chcit.mobile.R;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class ShipmentDetailFragment extends ScanFragment<ShipmentDetailPresenter> implements ShipmentDetailContract.View {

    @BindView(R.id.tv_shipment_detail_productName)
    AutofitTextView tvShipmentDetailProductName;
    @BindView(R.id.tv_shipment_detail_productSpec)
    AutofitTextView tvShipmentDetailProductSpec;
    @BindView(R.id.tv_shipment_detail_manufacturer)
    TextView tvShipmentDetailManufacturer;
    @BindView(R.id.tv_shipment_detail_productCode)
    TextView tvShipmentDetailProductCode;
    @BindView(R.id.tv_shipment_detail_uom)
    TextView tvShipmentDetailUom;
    @BindView(R.id.tv_shipment_detail_lot)
    TextView tvShipmentDetailLot;
    @BindView(R.id.tv_shipment_detail_guaranteeDate)
    TextView tvShipmentDetailGuaranteeDate;
    @BindView(R.id.tv_shipment_detail_pickListId)
    TextView tvShipmentDetailpickListId;
    @BindView(R.id.tv_shipment_detail_receving)
    TextView tvShipmentDetailReceving;
    @BindView(R.id.tv_shipment_detail_qtyLeft)
    TextView tvShipmentDetailQtyLeft;
    @BindView(R.id.tv_shipment_detail_qtyConfirmed)
    AppCompatEditText etShipmentDetailQtyPicked;
    @BindView(R.id.et_shipment_detail_qtyRejected)
    AppCompatEditText etRejected;
    @BindView(R.id.spinner_shipment_detail_locator)
    EditSpinner spinnerLocator;
    @BindView(R.id.bt_shipment_detail_ok)
    Button btShipmentDetailOk;
    @BindView(R.id.buttom_bar_group)
    LinearLayout buttomBarGroup;
    private ShipmentBean shipmentBean;
    private static List<ShipmentBean> mShipmentBeans;
    private Locator locator;//设置的货位
    private ArrayList<Locator> locators;//所有货位
    private String barcodeData;
    private List<MonitorCode> monitorCodes = new ArrayList<>();
    public static ShipmentDetailFragment newInstance(ShipmentBean data) {
        ShipmentDetailFragment fragment = new ShipmentDetailFragment();
        fragment.shipmentBean = data;
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerShipmentDetailComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .shipmentDetailModule(new ShipmentDetailModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_shipment_detail, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mCommonToolbar.setTitle("拣货明细");
        mCommonToolbar.getViewByTag(1).setOnClickListener(l->{
            pop();
        });
        initViewData();
        initSpinner();

    }

    /**
     * 通过此方法可以使 Fragment 能够与外界做一些交互和通信, 比如说外部的 Activity 想让自己持有的某个 Fragment 对象执行一些方法,
     * 建议在有多个需要与外界交互的方法时, 统一传 {@link Message}, 通过 what 字段来区分不同的方法, 在 {@link #setData(Object)}
     * 方法中就可以 {@code switch} 做不同的操作, 这样就可以用统一的入口方法做多个不同的操作, 可以起到分发的作用
     * <p>
     * 调用此方法时请注意调用时 Fragment 的生命周期, 如果调用 {@link #setData(Object)} 方法时 {@link Fragment#onCreate(Bundle)} 还没执行
     * 但在 {@link #setData(Object)} 里却调用了 Presenter 的方法, 是会报空的, 因为 Dagger 注入是在 {@link Fragment#onCreate(Bundle)} 方法中执行的
     * 然后才创建的 Presenter, 如果要做一些初始化操作,可以不必让外部调用 {@link #setData(Object)}, 在 {@link #initData(Bundle)} 中初始化就可以了
     * <p>
     * Example usage:
     * <pre>
     * public void setData(@Nullable Object data) {
     *     if (data != null && data instanceof Message) {
     *         switch (((Message) data).what) {
     *             case 0:
     *                 loadData(((Message) data).arg1);
     *                 break;
     *             case 1:
     *                 refreshUI();
     *                 break;
     *             default:
     *                 //do something
     *                 break;
     *         }
     *     }
     * }
     *
     * // call setData(Object):
     * Message data = new Message();
     * data.what = 0;
     * data.arg1 = 1;
     * fragment.setData(data);
     * </pre>
     *
     * @param data 当不需要参数时 {@code data} 可以为 {@code null}
     */
    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        pop();
    }

    private void initSpinner() {

        List<Locator> list = new ArrayList<>();//Arrays.asList("默认货位","理货货位","中药货位");
        spinnerLocator.setItemData(list);
        spinnerLocator.getEditText().setTextSize(15);
        spinnerLocator.setImageOnClickListener(new View.OnClickListener() {
            int i = 0;

            @Override
            public void onClick(View v) {
                if (i == 0) {
                    i++;

                }
            }
        });
        spinnerLocator.setOnItemChageClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                locator = locators.get(position);
            }
        });

    }

    private void initViewData() {
        assert shipmentBean != null;
        tvShipmentDetailProductName.setText(shipmentBean.getProductName());
        tvShipmentDetailProductSpec.setText(shipmentBean.getProductSpec());
        tvShipmentDetailManufacturer.setText(shipmentBean.getManufacturer());
        tvShipmentDetailProductCode.setText(shipmentBean.getProductCode());//不清楚 ？
        tvShipmentDetailUom.setText(shipmentBean.getUomName());
        tvShipmentDetailLot.setText(shipmentBean.getLot());
        tvShipmentDetailGuaranteeDate.setText(shipmentBean.getGuaranteeDate());
        tvShipmentDetailpickListId.setText((shipmentBean.getPickListId() + ""));
        tvShipmentDetailQtyLeft.setText((shipmentBean.getQtyLeft() + ""));
        etShipmentDetailQtyPicked.setText((shipmentBean.getQtyLeft() + ""));
        etRejected.setText("0");
        if (shipmentBean.getFromLocatorValue() != null) {
            locator = new Locator(shipmentBean.getFromLocatorId(), shipmentBean.getFromLocatorValue(), shipmentBean.getFromLocatorValue());
            spinnerLocator.setText(shipmentBean.getFromLocatorValue());
        }

    }

    private MaterialDialog buder;
    private SuperEditText etSupervision;
    private MonitorCodeAdapter monitorCodeAdapter;
    boolean isScanSupervision = false;//是否是扫描监管码
    void initScanDialog(){

        monitorCodeAdapter = new MonitorCodeAdapter(monitorCodes);
        buder = new MaterialDialog.Builder(mContext)
                .title("监管码绑定")
                .titleGravity(GravityEnum.CENTER)
                .customView(R.layout.dialog_scan_ok, true)
                .positiveText("确认")
                //.negativeText("取消")
                .autoDismiss(false)
                .onAny((dialog, which) -> {
                    isScanSupervision = false;
                    if (which == DialogAction.POSITIVE) {
                        //pickListMaId:1212,monitoringCode:['1111','1234','4444']
                        JSONArray monitoringCode = new JSONArray();
                        for(MonitorCode m :monitorCodes){
                            if(m.getId()>0){
                                monitoringCode.add(m.getCode());
                            }

                        }
                        if(monitoringCode.size()>0){
                            JSONObject data = new JSONObject();
                            data.put("pickListMaId",shipmentBean.getPickListMaId());
                            data.put("monitoringCode",monitoringCode);
                            mPresenter.doConfirm(HttpMethodContains.SHIPMENT_CODE_CREATE,data, dialog::dismiss);
                        }

                    }else if (which == DialogAction.NEGATIVE) {
                        // Toast.makeText(MainActivity.this, "不同意", Toast.LENGTH_LONG).show();
                        monitorCodeAdapter.getData().clear();
                        monitorCodeAdapter.notifyDataSetChanged();
                    }
                    //dialog.dismiss();
                })
                .build();


        //初始化Adapter
        RecyclerView recyclerView = buder.getCustomView().findViewById(R.id.rv_purchase_scan_list);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView.addItemDecoration(new RecycleViewDivider(mContext, LinearLayoutManager.HORIZONTAL, R.drawable.item_drivide));

        ItemDragAndSwipeCallback mItemDragAndSwipeCallback = new ItemDragAndSwipeCallback(monitorCodeAdapter);
        ItemTouchHelper mItemTouchHelper = new ItemTouchHelper(mItemDragAndSwipeCallback);
        mItemTouchHelper.attachToRecyclerView(recyclerView);
        OnItemDragListener listener = new OnItemDragListener() {
            @Override
            public void onItemDragStart(RecyclerView.ViewHolder viewHolder, int pos) {
                BaseViewHolder holder = ((BaseViewHolder) viewHolder);
//                holder.setTextColor(R.id.tv, Color.WHITE);
            }

            @Override
            public void onItemDragMoving(RecyclerView.ViewHolder source, int from, RecyclerView.ViewHolder target, int to) {

            }

            @Override
            public void onItemDragEnd(RecyclerView.ViewHolder viewHolder, int pos) {
                BaseViewHolder holder = ((BaseViewHolder) viewHolder);
//                holder.setTextColor(R.id.tv, Color.BLACK);
            }
        };
        OnItemSwipeListener onItemSwipeListener = new OnItemSwipeListener() {
            private int position = -1;
            @Override
            public void onItemSwipeStart(RecyclerView.ViewHolder viewHolder, int pos) {
                position = pos;
            }

            @Override
            public void clearView(RecyclerView.ViewHolder viewHolder, int pos) {

            }

            //删除item
            @Override
            public void onItemSwiped(RecyclerView.ViewHolder viewHolder, int pos) {
                //{pickListMaId:1212,monitoringCode:1111}
                if(pos!=-1){
                    position = pos;
                }
                MonitorCode  m = monitorCodes.get(position);
                if(m.getId() == 0){
                    JSONObject data = new JSONObject();
                    data.put("pickListMaId",shipmentBean.getPickListMaId());
                    data.put("monitoringCode",m.getCode());
                    mPresenter.doConfirm(HttpMethodContains.SHIPMENT_CODE_DELETE,data,()->{

                    });
                }
            }

            @Override
            public void onItemSwipeMoving(Canvas canvas, RecyclerView.ViewHolder viewHolder, float dX, float dY, boolean isCurrentlyActive) {
                canvas.drawColor(ContextCompat.getColor(mContext, R.color.green));

            }
        };

        //mItemDragAndSwipeCallback.setDragMoveFlags(ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT | ItemTouchHelper.UP | ItemTouchHelper.DOWN);
        mItemDragAndSwipeCallback.setSwipeMoveFlags(ItemTouchHelper.START | ItemTouchHelper.END);
        // 开启滑动删除
        monitorCodeAdapter.enableSwipeItem();
        monitorCodeAdapter.setOnItemSwipeListener(onItemSwipeListener);
        // 开启拖拽
        monitorCodeAdapter.enableDragItem(mItemTouchHelper);
        monitorCodeAdapter.setOnItemDragListener(listener);
        recyclerView.setAdapter(monitorCodeAdapter);
        Button button = buder.getCustomView().findViewById(R.id.button_scan_clear);
        button.setOnClickListener(l->{
            monitorCodeAdapter.getData().clear();
            monitorCodeAdapter.notifyDataSetChanged();
        });
        etSupervision = buder.getCustomView().findViewById(R.id.et_receiveScanCode_list_SerNo);
        etSupervision.setOnKeyListener((v, keyCode, event) -> {

            if (keyCode == KeyEvent.KEYCODE_ENTER && !etSupervision.getText().toString().isEmpty()) {

                addBindData();
                return true;
            } else {
                return false;
            }

        });

    }
    private void addBindData() {
        barcodeData = etSupervision.getText().toString();
        MonitorCode supervisionCode  =new MonitorCode(shipmentBean.getPickListMaId(),barcodeData);

        if (monitorCodeAdapter.getData().contains(supervisionCode)) {
            Toast.makeText(mContext, "绑定的数据重复！", Toast.LENGTH_LONG).show();
            return;
        }
        monitorCodeAdapter.addData(supervisionCode);

    }
    @OnClick({R.id.bt_shipment_detail_supervise, R.id.bt_shipment_detail_ok})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_shipment_detail_supervise:
                isScanSupervision = true;
           /*     if(shipmentBean.getSupervisionCodes()!=null){
                    monitorCodeAdapter.getData().addAll(monitorCodes);
                }*/
                mPresenter.getMonitorCodes(shipmentBean.getPickListMaId(),list ->{
                    monitorCodes.clear();
                    monitorCodes.addAll(list);
                    monitorCodeAdapter.notifyDataSetChanged();
                });
                buder.show();
                break;
            case R.id.bt_shipment_detail_ok:
                //  DialogUtil.showMsgDialog(getContext(),"",shipmentBean.toString());
                if (spinnerLocator.getText().isEmpty()) {
                    DialogUtil.showMsgDialog(getContext(), "提示", "请输入货位！");
                    return;
                }
                int locatorId = 0;
                if (locator == null) {
                    JSONObject data = new JSONObject();
                    data.put("value", spinnerLocator.getText());
                    mPresenter.getLocators(data,list->{
                       locator = list.get(0);
                       doConfirm();

                    });
                } else {
                    doConfirm();

                }

                break;
        }
    }
    private void doConfirm() {
        JSONObject params = new JSONObject();
        JSONArray lineData = new JSONArray();
        params.put("pickListJobId", shipmentBean.getPickListMaId());
        params.put("qtyConfirm", etShipmentDetailQtyPicked.getText().toString());
        params.put("qtyCancel",etRejected.getText().toString());

        lineData.add(params);
        JSONObject data = new JSONObject();
        data.put("pickListId", shipmentBean.getPickListId());//任务
        data.put("lineData", lineData); //拣货数量
        data.put("isAutoShipment","N");
        mPresenter.doConfirm(data,()->{
            setFragmentResult(RESULT_OK,null);
            pop();
        });

    }

    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        initScanDialog();

    }

    @Override
    protected void onBarcodeEventSuccess(String barcodeData) {
        if(isScanSupervision){
            etSupervision.setText(barcodeData);
            addBindData();
        }else{
            spinnerLocator.setText(barcodeData);
        }
    }
}
